<template>
  <div class="business-refunds-wrapper">
    <!-- 顶部标题栏 -->
    <header>
      <i class="fa fa-angle-left back-btn" @click="goBackToManage"></i>
      <p>退款申请管理</p>
      <i class="fa fa-refresh refresh-btn" @click="refreshRefundList" :class="{ 'refreshing': isRefreshing }"></i>
    </header>
    
    <!-- 标签导航栏 -->
    <div class="refund-tabs">
      <div 
        v-for="tab in tabs" 
        :key="tab.id"
        :class="['tab-item', { active: activeTab === tab.id }]"
        @click="activeTab = tab.id"
      >
        {{ tab.name }}
        <div class="tab-indicator" v-if="activeTab === tab.id"></div>
      </div>
    </div>
    
    <!-- 可滚动的主内容区域 -->
    <div class="main-content">
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading">
        <p>正在加载退款申请信息...</p>
      </div>
      
      <!-- 内容区域 -->
      <div v-else>
        <!-- 待审核标签页 -->
        <div v-if="activeTab === 'pending'" class="tab-content">
          <div v-if="pendingRefunds.length === 0" class="empty-state">
            <p>暂无待审核的退款申请</p>
          </div>
          <div v-else class="refund-list">
            <div 
              v-for="refund in pendingRefunds" 
              :key="refund.id"
              class="refund-card"
            >
              <!-- 订单基本信息 -->
              <div class="refund-header">
                <div class="order-info">
                  <span class="order-id">订单ID: {{ refund.orderId }}</span>
                  <span class="refund-date">申请时间: {{ formatDateTime(refund.applyTime) }}</span>
                </div>
                <div class="refund-status pending">待审核</div>
              </div>
              
              <!-- 退款原因 -->
              <div class="refund-reason">
                <h4>退款原因:</h4>
                <p>{{ refund.reason }}</p>
              </div>
              
              <div v-if="refund.detail" class="refund-detail">
                <h4>详细说明:</h4>
                <p>{{ refund.detail }}</p>
              </div>
              
              <!-- 操作按钮 -->
              <div class="refund-actions">
                <button 
                  class="reject-btn" 
                  @click="openRejectForm(refund)"
                >
                  拒绝退款
                </button>
                <button 
                  class="approve-btn" 
                  @click="approveRefund(refund.id)"
                >
                  同意退款
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 已处理标签页 -->
        <div v-else class="tab-content">
          <div v-if="processedRefunds.length === 0" class="empty-state">
            <p>暂无已处理的退款申请</p>
          </div>
          <div v-else class="refund-list">
            <div 
              v-for="refund in processedRefunds" 
              :key="refund.id"
              class="refund-card"
            >
              <!-- 订单基本信息 -->
              <div class="refund-header">
                <div class="order-info">
                  <span class="order-id">订单ID: {{ refund.orderId }}</span>
                  <span class="refund-date">申请时间: {{ formatDateTime(refund.applyTime) }}</span>
                </div>
                <div 
                  :class="['refund-status', refund.status === 1 ? 'approved' : 'rejected']"
                >
                  {{ refund.status === 1 ? '已批准' : '已拒绝' }}
                </div>
              </div>
              
              <!-- 退款原因 -->
              <div class="refund-reason">
                <h4>退款原因:</h4>
                <p>{{ refund.reason }}</p>
              </div>
              
              <div v-if="refund.detail" class="refund-detail">
                <h4>详细说明:</h4>
                <p>{{ refund.detail }}</p>
              </div>
              
              <!-- 拒绝原因 -->
              <div v-if="refund.status === 2 && refund.rejectReason" class="reject-reason">
                <h4>拒绝原因:</h4>
                <p>{{ refund.rejectReason }}</p>
              </div>
              
              <!-- 处理时间 -->
              <div class="process-time">
                <h4>处理时间:</h4>
                <p>{{ formatDateTime(refund.processTime) }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 拒绝退款弹窗 -->
    <div v-if="showRejectForm" class="reject-form-overlay" @click.self="closeRejectForm">
      <div class="reject-form-container">
        <div class="reject-form-header">
          <h3>拒绝退款原因</h3>
          <span class="close-btn" @click="closeRejectForm">&times;</span>
        </div>
        <div class="reject-form-content">
          <textarea 
            v-model="rejectReason" 
            placeholder="请输入拒绝退款的原因，以便用户了解" 
            maxlength="200"
          ></textarea>
          <div class="char-count">{{ rejectReason.length }}/200</div>
        </div>
        <div class="reject-form-footer">
          <button class="cancel-btn" @click="closeRejectForm">取消</button>
          <button 
            class="submit-btn" 
            @click="rejectRefund()"
            :disabled="!rejectReason.trim()"
          >
            确认拒绝
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { refundApi } from '../api';
import { useRouter } from 'vue-router';

// 获取路由实例
const router = useRouter();

// 标签页数据
const tabs = [
  { id: 'pending', name: '待处理' },
  { id: 'processed', name: '已处理' }
];
const activeTab = ref('pending');

// 加载状态
const isLoading = ref(true);
const isRefreshing = ref(false);

// 退款数据
const allRefunds = ref([]);
const currentRefund = ref(null);
const rejectReason = ref('');
const showRejectForm = ref(false);

// 计算属性：待审核退款
const pendingRefunds = computed(() => {
  return allRefunds.value.filter(refund => refund.status === 0);
});

// 计算属性：已处理退款
const processedRefunds = computed(() => {
  return allRefunds.value.filter(refund => refund.status === 1 || refund.status === 2);
});

// 初始化数据
const init = async () => {
  isLoading.value = true;
  try {
    // 获取商家信息
    const businessInfoStr = localStorage.getItem('business');
    if (!businessInfoStr) {
      console.error('未找到商家信息');
      return;
    }
    
    const businessInfo = JSON.parse(businessInfoStr);
    const businessId = businessInfo.id;
    
    // 获取所有退款申请
    const refunds = await refundApi.getRefundsByBusinessId(businessId);
    allRefunds.value = refunds;
    
    console.log('获取退款申请成功:', refunds);
  } catch (error) {
    console.error('获取退款申请失败:', error);
    alert('获取退款申请失败，请稍后重试');
  } finally {
    isLoading.value = false;
  }
};

// 刷新退款列表
const refreshRefundList = async () => {
  if (isRefreshing.value) return;
  
  isRefreshing.value = true;
  try {
    await init();
  } finally {
    isRefreshing.value = false;
  }
};

// 打开拒绝退款表单
const openRejectForm = (refund) => {
  currentRefund.value = refund;
  rejectReason.value = '';
  showRejectForm.value = true;
};

// 关闭拒绝退款表单
const closeRejectForm = () => {
  showRejectForm.value = false;
};

// 批准退款
const approveRefund = async (refundId) => {
  if (!confirm('确认批准此退款申请?')) {
    return;
  }
  
  try {
    const result = await refundApi.processRefund(refundId, true);
    console.log('批准退款成功:', result);
    alert('已批准退款申请');
    
    // 刷新列表
    refreshRefundList();
  } catch (error) {
    console.error('批准退款失败:', error);
    alert(`批准退款失败: ${error.message || '请稍后重试'}`);
  }
};

// 拒绝退款
const rejectRefund = async () => {
  if (!currentRefund.value) return;
  
  try {
    const result = await refundApi.processRefund(
      currentRefund.value.id,
      false,
      rejectReason.value
    );
    
    console.log('拒绝退款成功:', result);
    alert('已拒绝退款申请');
    
    // 关闭表单并刷新列表
    closeRejectForm();
    refreshRefundList();
  } catch (error) {
    console.error('拒绝退款失败:', error);
    alert(`拒绝退款失败: ${error.message || '请稍后重试'}`);
  }
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未知时间';
  
  try {
    const date = new Date(dateTimeStr);
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return dateTimeStr;
    }
    
    // 格式化为 "YYYY-MM-DD HH:MM:SS" 格式
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateTimeStr;
  }
};

// 返回店铺管理中心
const goBackToManage = () => {
  router.push('/businessManage');
};

// 初始化
onMounted(() => {
  init();
});
</script>

<style scoped>
.business-refunds-wrapper {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

/****************** 顶部标题栏 ******************/
header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  font-weight: 500;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  z-index: 1000;
}

header .back-btn {
  position: absolute;
  left: 4vw;
  font-size: 5vw;
  color: #fff;
  cursor: pointer;
  transition: transform 0.3s ease;
}

header .back-btn:active {
  transform: translateX(-2px);
}

header .refresh-btn {
  position: absolute;
  right: 4vw;
  font-size: 4vw;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 2vw;
}

header .refresh-btn:hover {
  opacity: 0.8;
}

header .refresh-btn.refreshing {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/****************** 标签导航栏 ******************/
.refund-tabs {
  width: 100%;
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 0 2vw;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  z-index: 900;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 3vw 0;
  font-size: 3.8vw;
  color: #666;
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
}

.tab-item.active {
  color: #0097ff;
  font-weight: 600;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 0.6vw;
  background-color: #0097ff;
  border-radius: 1vw 1vw 0 0;
  transition: all 0.3s ease;
}

.tab-content {
  padding: 3vw;
}

/****************** 主内容区域 ******************/
.main-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding-bottom: 10vw;
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
}

/****************** 加载状态 ******************/
.loading {
  width: 100%;
  margin-top: 15vw;
  padding: 10vw;
  text-align: center;
  color: #666;
  font-size: 4vw;
}

/****************** 空状态 ******************/
.empty-state {
  width: 100%;
  padding: 15vw 4vw;
  text-align: center;
  color: #999;
  font-size: 3.8vw;
  background-color: #f9f9f9;
  margin: 2vw 0;
  border-radius: 8px;
}

/****************** 退款卡片 ******************/
.refund-list {
  display: flex;
  flex-direction: column;
  gap: 3vw;
}

.refund-card {
  background-color: #fff;
  border-radius: 2vw;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 4vw;
  margin-bottom: 3vw;
}

.refund-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3vw;
  padding-bottom: 3vw;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 1vw;
}

.order-id {
  font-size: 3.8vw;
  font-weight: 600;
  color: #333;
}

.refund-date {
  font-size: 3.2vw;
  color: #999;
}

.refund-status {
  padding: 1vw 2vw;
  border-radius: 1vw;
  font-size: 3.2vw;
  font-weight: 500;
  color: #fff;
}

.refund-status.pending {
  background-color: #ff9800;
}

.refund-status.approved {
  background-color: #4caf50;
}

.refund-status.rejected {
  background-color: #f44336;
}

.refund-reason, .refund-detail, .reject-reason, .process-time {
  margin-bottom: 3vw;
}

.refund-reason h4, .refund-detail h4, .reject-reason h4, .process-time h4 {
  font-size: 3.6vw;
  font-weight: 600;
  color: #333;
  margin-bottom: 1vw;
}

.refund-reason p, .refund-detail p, .reject-reason p, .process-time p {
  font-size: 3.6vw;
  color: #666;
  line-height: 1.5;
}

.refund-actions {
  display: flex;
  justify-content: flex-end;
  gap: 3vw;
  margin-top: 3vw;
  padding-top: 3vw;
  border-top: 1px solid #eee;
}

.reject-btn, .approve-btn {
  padding: 2vw 4vw;
  border-radius: 1vw;
  font-size: 3.6vw;
  font-weight: 500;
  border: none;
  cursor: pointer;
}

.reject-btn {
  background-color: #fff;
  color: #f44336;
  border: 1px solid #f44336;
}

.approve-btn {
  background-color: #4caf50;
  color: #fff;
}

/****************** 拒绝理由弹窗 ******************/
.reject-form-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.reject-form-container {
  width: 85%;
  max-width: 500px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.reject-form-header {
  padding: 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.reject-form-header h3 {
  margin: 0;
  font-size: 4.5vw;
  font-weight: 600;
  color: #333;
}

.close-btn {
  font-size: 6vw;
  color: #999;
  cursor: pointer;
}

.reject-form-content {
  padding: 4vw;
}

textarea {
  width: 100%;
  height: 30vw;
  padding: 2vw;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  font-size: 3.5vw;
  color: #333;
  box-sizing: border-box;
}

.char-count {
  text-align: right;
  font-size: 3.2vw;
  color: #999;
  margin-top: 1vw;
}

.reject-form-footer {
  padding: 3vw 4vw;
  display: flex;
  justify-content: flex-end;
  gap: 3vw;
  border-top: 1px solid #eee;
}

.cancel-btn, .submit-btn {
  padding: 2vw 5vw;
  border: none;
  border-radius: 4px;
  font-size: 3.8vw;
  cursor: pointer;
  transition: all 0.2s ease;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.submit-btn {
  background-color: #f44336;
  color: white;
}

.submit-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style> 